﻿using Microsoft.AspNetCore.Mvc.ApplicationModels;
using System;
using XUCore.Extensions;
using XUCore.NetCore.DynamicWebApi.Helper;

namespace XUCore.NetCore.DynamicWebApi
{
    internal class DefaultActionRouteFactory : IActionRouteFactory
    {
        public string GetActionRoute(string areaName, string controllerName, ActionModel action, AttributeRouteModel attributeRouteModel)
        {
            var attr = ReflectionHelper.GetSingleAttributeOrDefaultByFullSearch<DynamicWebApiAttribute>(action.Controller.ControllerType);

            if (attr == null)
                throw new Exception($"{controllerName}，未设置 {nameof(DynamicWebApiAttribute)}");

            var apiPreFix = attr.ApiPrefix.NotEmpty() ? attr.ApiPrefix : action.GetApiPrefix();

            var route = AppConsts.GetRestFulRouteTemplate?.Invoke(new ReouteOptions
            {
                ControllerName = controllerName,
                AreaName = areaName,
                ApiPreFix = apiPreFix,
                ActionName = attributeRouteModel == null || attributeRouteModel.Template.IsEmpty() ? action.ActionName : attributeRouteModel.Template,
                Version = attr.Version
            });

            if (route.IsEmpty())
                throw new Exception($"路由模板返回错误");

            return route.Replace("//", "/");
        }
    }
}